<?php
class Member {
	private $member_id;
	private $email;
	private $alias;
	private $gender;
	private $verified;
	private $balance;
	private $score;
	private $activityBad;
	private $activityGood;
	private $sponsorBad;
	private $sponsorGood;
	private $birthday;
	private $avatar;
	private $token;
	
	private $presenCountry;
	private $presenProvince;
	private $presenCity;
	private $presenDistrict;
	
  	public function __construct($registry) {
		$this->config = $registry->get('config');
		$this->db = $registry->get('db');
		$this->request = $registry->get('request');
		$this->session = $registry->get('session');
		
		if ( ( !isset($this->session->data['member_id']) || !isset($this->session->data['login_token']) ) && isset($this->request->cookie['account']) ) {
			$cookie_account = json_decode(htmlspecialchars_decode($this->request->cookie['account'], ENT_COMPAT));
			$check_token = $this->db->query("SELECT ID FROM " . DB_PREFIX . "account_token WHERE AccountID='" . (int)$cookie_account->id . "' AND Token='" . $this->db->escape($cookie_account->token) . "' AND Expires > CURRENT_TIMESTAMP;");
			if ($check_token->num_rows > 0) {
				$this->session->data['member_id'] = (int)$cookie_account->id;
				$this->session->data['login_token'] = $cookie_account->token;
			}
			else {
				$this->logout();
			}
			unset($check_token);
			unset($cookie_account);
		}
				
		if (isset($this->session->data['member_id']) && isset($this->session->data['login_token'])) { 
			$query = $this->db->query("SELECT AC.ID AS ID, Email, Alias, Gender, Birthday, PresentPlaceCountryID, PresentPlaceProvinceID, PresentPlaceCityID, PresentPlaceDistrictID, IsVerified, Balance, Score, ActivityBad, ActivityGood, SponsorBad, SponsorGood, AvatarID, AV.Domain, AV.Directory, AV.Filename  FROM " . DB_PREFIX . "account AS AC LEFT JOIN " . DB_PREFIX . "account_avatar AS AV ON AC.AvatarID = AV.ID WHERE AC.ID = '" . (int)$this->session->data['member_id'] . "' AND Status = '1'");
			
			if ($query->num_rows) {
				$this->member_id 			= $query->row['ID'];
				$this->email 				= $query->row['Email'];
				$this->alias 				= $query->row['Alias'];
				$this->gender 				= $query->row['Gender'];
				$this->verified 			= $query->row['IsVerified'] ? true : false;
				$this->balance 				= $query->row['Balance'];
				$this->score 				= $query->row['Score'];
				$this->activityBad 			= $query->row['ActivityBad'];
				$this->activityGood 		= $query->row['ActivityGood'];
				$this->sponsorBad 			= $query->row['SponsorBad'];
				$this->sponsorGood 			= $query->row['SponsorGood'];
				$this->birthday 			= $query->row['Birthday'];
				$this->avatar 				= array('avatarID' => $query->row['AvatarID'], 'domain' => $query->row['Domain'], 'directory' => $query->row['Directory'], 'filename' => $query->row['Filename']);
				
				$this->presenCountry 		= $query->row['PresentPlaceCountryID'];
				$this->presenProvince 		= $query->row['PresentPlaceProvinceID'];
				$this->presenCity 			= $query->row['PresentPlaceCityID'];
				$this->presenDistrict 		= $query->row['PresentPlaceDistrictID'];
				
				$this->token 				= $this->session->data['login_token'];
							
      			$this->db->query("UPDATE " . DB_PREFIX . "account SET LastIp = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', LastDatetime=NOW() WHERE ID = '" . (int)$this->member_id . "'");
				/*
				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "account_ip WHERE accountID = '" . (int)$this->session->data['member_id'] . "' AND ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "'");
				
				if (!$query->num_rows) {
					$this->db->query("INSERT INTO " . DB_PREFIX . "account_ip SET accountID = '" . (int)$this->session->data['member_id'] . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', AddDatetime = NOW()");
				}
				*/
			} else {
				$this->logout();
			}
		} 
	}
		
  	public function login($email, $password, $expires = NULL, $type = 'password') {
  		$whereKey = "Password = '" . $this->db->escape(sha1(md5($password))) . "'";
  		switch ( $type ) {
  			case 'qq' :
  				$whereKey = "QQOpenid = '" . $this->db->escape($password) . "'";
  				break;
  		}
		$query = $this->db->query("SELECT 
				ID, 
				Email, 
				Alias, 
				Gender, 
				Birthday, 
				PresentPlaceCountryID, 
				PresentPlaceProvinceID, 
				PresentPlaceCityID, 
				PresentPlaceDistrictID, 
				IsVerified, 
				Balance, 
				Score, 
				ActivityBad, 
				ActivityGood, 
				SponsorBad, 
				SponsorGood, 
				AvatarID, 
				Status 
				FROM " . DB_PREFIX . "account WHERE LOWER(Email) = '" . $this->db->escape(strtolower($email)) . "' AND " . $whereKey);
		
		if ($query->num_rows) {
			if ( $query->row['Status'] == 2)
				return 2;
			if ( $query->row['Status'] == 3)
				return 3;
			if (!$query->row['IsVerified'])
				return 4;
			
			$this->session->data['member_id'] = $query->row['ID'];
									
			$this->member_id 			= $query->row['ID'];
			$this->email 				= $query->row['Email'];
			$this->alias 				= $query->row['Alias'];
			$this->gender 				= $query->row['Gender'];
			$this->verified 			= $query->row['IsVerified'] ? true : false;
			$this->balance 				= $query->row['Balance'];
			$this->score 				= $query->row['Score'];
			$this->activityBad 			= $query->row['ActivityBad'];
			$this->activityGood 		= $query->row['ActivityGood'];
			$this->sponsorBad 			= $query->row['SponsorBad'];
			$this->sponsorGood 			= $query->row['SponsorGood'];
			$this->birthday 			= $query->row['Birthday'];
			
			$this->presenCountry 		= $query->row['PresentPlaceCountryID'];
			$this->presenProvince 		= $query->row['PresentPlaceProvinceID'];
			$this->presenCity 			= $query->row['PresentPlaceCityID'];
			$this->presenDistrict 		= $query->row['PresentPlaceDistrictID'];
			
			$this->avatar 				= array('avatarID' => $query->row['AvatarID'], 'domain' => '', 'directory' => '', 'filename' => '');
			
			$query = $this->db->query("SELECT Domain, Directory, Filename FROM " . DB_PREFIX . "account_avatar WHERE ID='" . $this->avatar['avatarID'] . "'");
			if ($query->num_rows) {
				$this->avatar['domain'] 	= $query->row['Domain'];
				$this->avatar['directory'] 	= $query->row['Directory'];
				$this->avatar['filename'] 	= $query->row['Filename'];
			}
			
			$token = $this->createToken();
			
			if (!is_int($expires)) {
				$expires = 12 * 60 * 60;
			} 
			
			$this->db->query("DELETE FROM " . DB_PREFIX . "account_token WHERE AccountID='" . (int)$this->member_id . "' AND Expires <= CURRENT_TIMESTAMP;");
			
			$this->db->query("INSERT INTO " . DB_PREFIX . "account_token SET
				AccountID='" . (int)$this->member_id . "',
				Token='" . $this->db->escape($token) . "',
				Expires='" . date('Y-m-d H:i:s', time() + (int)$expires) . "',
				Device='0'");
			
			$this->token = $token;
			$this->session->data['login_token'] = $this->token;
          	
			$this->db->query("UPDATE " . DB_PREFIX . "account SET LastIp = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', LastDatetime=NOW() WHERE ID = '" . (int)$this->member_id . "'");
			
	  		return 1;
    	} else {
      		return 0;
    	}
  	}
  	
  	private function createToken($prefix = '') {
  		return $prefix . md5 ( $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'] . time() . mt_rand() );
  	}
  	
  	public function writeCookie($expires = 43200) {
  		$accout_data = array(
  			'id'	 => $this->member_id,
  			'email'	 => $this->email,
  			'alias'	 => $this->alias,
  			'gender' => $this->gender,
  			'avatar' => $this->avatar,
  			'token'	 => $this->token
  		);
  		
  		setcookie("account", json_encode($accout_data), time() + (int)$expires, '/', COOKIE_DOMAIN);
  	}
  	
	public function logout() {
		if ( isset($this->session->data['login_token']) ) {
			$this->db->query("DELETE FROM " . DB_PREFIX . "account_token WHERE Token='" . $this->db->escape($this->session->data['login_token']) . "';");
		}
		unset($this->session->data['member_id']);
		unset($this->session->data['login_token']);

		$this->member_id 			= NULL;
		$this->email 				= NULL;
		$this->alias 				= NULL;
		$this->gender 				= NULL;
		$this->verified 			= NULL;
		$this->balance 				= NULL;
		$this->score 				= NULL;
		$this->activityBad 			= NULL;
		$this->activityGood 		= NULL;
		$this->sponsorBad 			= NULL;
		$this->sponsorGood 			= NULL;
		$this->birthday 			= NULL;
		$this->avatar['avatarID'] 	= NULL;
		$this->avatar['domain'] 	= NULL;
		$this->avatar['directory'] 	= NULL;
		$this->avatar['filename'] 	= NULL;
		
		$this->presenCountry 		= NULL;
		$this->presenProvince 		= NULL;
		$this->presenCity 			= NULL;
		$this->presenDistrict 		= NULL;
		
		$this->token				= NULL;
		
		setcookie("account", "", time() - 3600, '/', COOKIE_DOMAIN);
  	}
  
  	public function isLogged() {
    	return $this->member_id && $this->token;
  	}

  	public function getId() {
    	return $this->member_id;
  	}
  	
  	public function getToken() {
  		return $this->token;
  	}
  	
  	public function getEmail() {
		return $this->email;
  	}
  
  	public function getAlias() {
		return $this->alias;
  	}
  
  	public function getGender() {
		return $this->gender;
  	}
  
  	public function getVerified() {
		return $this->verified;
  	}
  
  	public function getBalance() {
		return $this->balance;
  	}
	
  	public function getScore() {
		return $this->score;	
  	}

  	public function getActivityValue() {
		return array('bad' => $this->activityBad, 'good' => $this->activityGood);	
  	}
	
  	public function getSponsorValue() {
		return array('bad' => $this->sponsorBad, 'good' => $this->sponsorGood);		
  	}
	
  	public function getBirthday() {
		return $this->birthday;
  	}	
		
  	public function getAvatar() {
  		$this->avatar['id'] = $this->member_id;
  		$this->avatar['gender'] = $this->gender;
		return $this->avatar;	
  	}
	
	public function getPresent() {
		return array('country' => $this->presenCountry, 'province' => $this->presenProvince, 'city' => $this->presenCity, 'district' => $this->presenDistrict);	
  	}
}
?>